package com.linQing.waterWork.config;

import com.linQing.waterWork.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import java.net.URISyntaxException;

@Configuration
public class MongoConfig extends MongoAutoConfiguration {

    @Value("${spring.data.mongodb.database}")
    private String mongoDatabase;
    @Value("${spring.data.mongodb.username}")
    private String mongoUsername;
    @Value("${spring.data.mongodb.password}")
    private String mongoPassword;
    @Value("${spring.data.mongodb.authentication-database}")
    private String mongoAuthenticationDatabase;
    @Value("${spring.data.mongodb.host}")
    private String mongoHost;
    @Value("${spring.data.mongodb.port}")
    private String mongoPort;

    @Autowired
    public MongoConfig(MongoProperties mongoProperties) {

    }

    @Bean
    protected String currentYear() {
        return DateUtils.getCurrentYear();
    }

    @Bean
    public MongoDatabaseFactory mongoDatabaseFactory() throws URISyntaxException {

        String newDatabaseName = mongoDatabase + currentYear();
        // 构建新的URI
        String newUri = String.format("mongodb://%s:%s@%s:%d/%s?authSource=%s",
                mongoUsername,mongoPassword,mongoHost,Integer.parseInt(mongoPort),newDatabaseName,mongoAuthenticationDatabase);
        return new SimpleMongoClientDatabaseFactory(newUri);
    }

    @Bean
    public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory) {
        return new MongoTemplate(mongoDatabaseFactory);
    }
}